using Domain;
using ErrorCode;
using MediatR;
using SqlSugar;
using SqlSugar.Extensions;
using WriteAPI.Command.Material;

namespace WriteAPI.CommandHandle.Material
{
    public class GetMaterialCommandHandler : IRequestHandler<GetMaterialCommand, APIPaging<MaterialReplenishment>>
    {
        private readonly ISqlSugarClient db;


        public GetMaterialCommandHandler(ISqlSugarClient db)
        {
            this.db = db;

        }
        public async Task<APIPaging<MaterialReplenishment>> Handle(GetMaterialCommand request, CancellationToken cancellationToken)
        {
            APIPaging<MaterialReplenishment> paging = new APIPaging<MaterialReplenishment>();

            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Console.WriteLine("Generated SQL:\n" + sql);
            };



            // 查询主表并包含子表数据
            var query = db.Queryable<MaterialReplenishment>()
                .Includes(x => x.MaterialDetails).OrderByDescending(x => x.Id); // 自动加载子表


            // 计算总记录数(优化性能)
            paging.TotalCount = await query.CountAsync();
            //分页数
            paging.TotalPage = (int)Math.Ceiling((double)paging.TotalCount / request.size);

            // 分页查询数据(优化性能)
            var result = await query.ToPageListAsync(request.index, request.size, paging.TotalCount);


            //数据
            paging.Items = result;



            return await Task.FromResult(paging);
        }
    }
}



